package com.iflytek.ossp.auth.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.iflytek.ossp.auth.entity.MenuInfo;
import com.iflytek.ossp.auth.entity.RoleInfo;
import com.iflytek.ossp.auth.entity.RoleMenuInfo;
import com.iflytek.ossp.auth.entity.UserInfo;
import com.iflytek.ossp.dao.JpaDao;

@Service("roleService")
public class RoleService {

	@Resource
	private JpaDao authDao;
	
	@Resource
	private UserService userService;

	public RoleInfo getRoleById(Long id) {
		if (id == null) {
			return null;
		}
		return authDao.find(RoleInfo.class, id);
	}

	public List<RoleInfo> getAllRoles() {
		return authDao.find("from RoleInfo order by createTime");
	}

	public List<RoleInfo> getRolesByCreator(Long userId) {
		return authDao
				.find("select distinct roleInfo from RoleInfo roleInfo, UserInfo userInfo where"
						+ " roleInfo.creator = userInfo.loginName and userInfo.id = ?",
						userId);
	}
	
	public List<RoleInfo> getRolesByUser(Long userId) {
		return authDao.find("select distinct rui.role from RoleUserInfo rui"
				+ " where rui.user.id=? order by rui.role.createTime", userId);
	}

	public void saveRole(RoleInfo role) {
		Date time = new Date();
		if (role.getCreator() == null) {
			role.setCreator(UserService.getCurrentLoginName());
		} else {
			role.setUpdator(UserService.getCurrentLoginName());
		}
		if (role.getCreateTime() == null) {
			role.setCreateTime(time);
		} else {
			role.setUpdateTime(time);
		}
		authDao.save(role);
	}
	
	
	public UserInfo getCreator(Long id) {
		RoleInfo ri = getRoleById(id);
		return userService.getUserByLoginName(ri.getCreator());
	}
	
	public void saveRoleMenu(Long roleId, Long[] menuIds) {
		if (menuIds == null) {
			return;
		}
		RoleInfo roleInfo = getRoleById(roleId);
		if (roleInfo == null) {
			return;
		}
		authDao.bulkUpdate("delete from RoleMenuInfo where role.id=?", roleId);
		for (Long menuId : menuIds) {
			MenuInfo menuInfo = authDao.find(MenuInfo.class, menuId);
			if (menuInfo == null) {
				continue;
			}
			RoleMenuInfo rmi = new RoleMenuInfo();
			rmi.setRole(roleInfo);
			rmi.setMenu(menuInfo);
			authDao.save(rmi);
		}
	}

	@Transactional
	public void deleteRole(Long id) {
		authDao.bulkUpdate("delete from RoleMenuInfo where role.id=?", id);
		authDao.bulkUpdate("delete from RoleUserInfo where role.id=?", id);
		authDao.bulkUpdate("delete from RoleInfo where id=?", id);
	}

}
